import { Controller } from '@nestjs/common';
import {
  Ctx,
  EventPattern,
  MessagePattern,
  NatsContext,
  Payload,
} from '@nestjs/microservices';

@Controller()
export class AppController {
  // 【通讯1】微服务接收外面的消息
  @MessagePattern({ cmd: 'sum' })
  // 默认接收
  // accumulate(data: number[]): number {
  // 获取上下文信息（连接对象）
  accumulate(@Payload() data: number[], @Ctx() context: NatsContext): number {
    console.log('🚀 ~ app.controller.ts:18 ~ accumulate ~ context:', context);
    return (data || []).reduce((a, b) => a + b);
  }

  // 【通讯2】广播方式的通讯方式，定义事件
  @EventPattern('user_created')
  handleUserCreated(data: Record<string, unknown>) {
    console.log('🚀 ~ app.controller.ts:26 ~ handleUserCreated ~ data:', data);
    // business logic
    return JSON.stringify(data);
  }

  @EventPattern('user_created')
  handleUserCreated2(data: Record<string, unknown>) {
    console.log('🚀 ~ app.controller.ts:32 ~ handleUserCreated2 ~ data:', data);
    // business logic
    return JSON.stringify({
      ...data,
      name: 'test',
    });
  }
}
